<script>
import Desgin from './create-desgin'
import {Toast, Notify} from "vant";
import axios from "axios";
import {Topology} from '@/canvas/@topology/core'

const width = isNaN(parseInt(localStorage.getItem('width'))) ? 0 : parseInt(localStorage.getItem('width'))
const height = isNaN(parseInt(localStorage.getItem('height'))) ? 0 : parseInt(localStorage.getItem('height'))
console.log('height',width,height)

const canvasOptions = {
    width: width,
    height: height,
    lineName: 'line',
    minScale: 0,
    maxScale: 50,
    // 连线颜色
    color: '#fff',
    hoverColor: 'rgba(0,0,0,0)',
    font: {
        color: '#fff',
        fontSize: 14,
        textBaseline: 'bottom'
    },
    // 键盘事件 如 删除 移动
    keydown: -1,
    // 缩放 如 ctrl + mousewheel 缩放
    disableScale: true,
    // 移动 如 ctrl + mouse 移动
    disableTranslate: false,
    disableEmptyLine: false,
    autoAnchor: false,
    autoExpandDistance: 0,
    cacheLen: 10000,
    hideAnchor: true // 隐藏锚点
}

export default {
    extends: Desgin,
    data() {
      return {
          screenWidth: canvasOptions.width,
          screenHeight: canvasOptions.height,
          interval: 0
      }
    },
  methods: {
         /**
       *  初始化路由参数
       */
      initRouteQuery() {
             Toast.loading({
                 message: '',
                 duration: 0
             })
        const { token, id } = this.$route.query
        localStorage.setItem('token', token || '')
        this.cardId = id
        axios({
          method: 'GET',
          url: this.baseUrl +`/api/v1/card/detail/${id}`,
          headers: {
            'X-UNI-TOKEN': localStorage.getItem('token'),
          },
        }).then(res => {
          this.cardDetail = res.data.data
          this.initCanvas()
          Toast.clear()
          
        })
      },
      /**
       *  保存
       */
      handleSave() {
          Toast.loading({
              message: '保存中',
              duration: 0
          })
          setTimeout(() => {
              this.handleSaveImage().then(res => {
                  wx.miniProgram.redirectTo({
                      url: '/pages/myDetail/index?id=' + this.cardDetail.cardId
                  })
              })
          })
      },
      async handleSaveImage(isUpload = false) {
          return new Promise(async (resolve,reject) => {
            let imageUrl = this.cardDetail.imgUrl
            if (!isUpload) {
              imageUrl = await this.uploadImage()
              clearInterval(this.interval)
              this.interval = null
            }
              axios({
                  method: 'POST',
                  url: this.baseUrl + '/api/v1/card/edit',
                  headers: {
                      'X-UNI-TOKEN': localStorage.getItem('token'),
                  },
                  data: {
                      "cardId": this.cardDetail.cardId,
                      "configure": JSON.stringify(this.canvas.data),
                      "imgUrl": imageUrl,
                      "title": this.cardDetail.title
                  }
              }).then(res => {
                  if (res.data.code === 200) {
                      if (this.interval) {
                        Notify('保存成功')
                      } else {
                        Toast.success('保存成功')
                      }
                      resolve(this.cardDetail.cardId)
                  } else {
                      reject()
                      Toast.fail(res.data.msg)
                  }
              }).catch((err) => {
                  Toast.fail(err || '请求出错')
              })
          })
      },
        /**
         *  初始化画布
         */
        initCanvas() {
            this.canvas = null
            canvasOptions.on = this.onMessage
            this.canvas = new Topology('canvasDom', canvasOptions)
            setTimeout(() => {
                if (this.cardDetail.configure) {
                    if (typeof this.cardDetail.configure === 'string') {
                        this.cardDetail.configure = JSON.parse(this.cardDetail.configure)
                        this.cardDetail.configure.pens.forEach(pen => {
                            if (pen.rect.width >= this.screenWidth) {
                                pen.rect.width = this.screenWidth
                                pen.rect.x = 0
                            }
                            if (pen.rect.height >= this.screenHeight) {
                                pen.rect.height = (this.screenHeight + 10)
                                pen.rect.y = 0
                            }
                        })
                    }
                    this.canvas.open(this.cardDetail.configure)
                }
                if (this.$route.query.UPLOAD_FILE) {
                    this.canvas.addNode({
                        rect: {
                            x: 170,
                            y: 75,
                            width: 50,
                            height: 50
                        },
                        image: this.$route.query.UPLOAD_FILE,
                        name: 'image'
                    },true)
                }
                console.log(this.canvas.getRect().width, this.canvas)
                if (this.canvas.getRect().width < this.canvas.canvas.width) {
                    this.canvas.scaleTo(this.screenWidth / 250, { x: 0, y: 0}, true)
                }
                this.canvas.data.bkColor = '#ffffff'
                this.canvas.render()
                this.interval = setInterval(() => {
                    this.handleSaveImage()
                },30000)
            },0)
        },
    },
    beforeDestroy() {
        clearInterval(this.interval)
        this.interval = 0
    }
}
</script>
